package com.itheima.stock.service.imp;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.Constants;
import com.itheima.stock.dto.LoginDTO;
import com.itheima.stock.entity.SysUser;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.exception.Exceptions;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import com.itheima.stock.vo.LoginVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private final IdWorkers idWorkers;
    private final Cache cache;
    private static final int FOUR = 4;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserServiceImpl(Cache cache, IdWorkers idWorkers) {
        this.cache = cache;
        this.idWorkers = idWorkers;

    }

    @Override
    public CaptchaVO captcha() {
        String random = RandomStringUtils.randomNumeric(FOUR);
        String redisKey = RedisKeyUtil.gennerateKey(Constants.CAPTCHA_PREFIX, idWorkers.nextStrId());
        cache.set(redisKey,random, Constants.CAPTCHA_EXPIRE_TIME);
        return CaptchaVO.builder().code(random).rkey(redisKey).build();
    }

    @Override
    public LoginVO login(LoginDTO dto) {
       if(ObjectUtils.isEmpty(dto)||
        ObjectUtils.isEmpty(dto.getUsername())||
        ObjectUtils.isEmpty(dto.getPassword())||
        ObjectUtils.isEmpty(dto.getCode())||
        ObjectUtils.isEmpty(dto.getRkey())){
           Exceptions.cast(CodeEnum.DATA_ERROR);
       }
       String key = dto.getRkey();
       String code = cache.get(key);
       Boolean equals = StringUtils.equals(code, dto.getCode());
       if(!equals){
           Exceptions.cast(CodeEnum.SYSTEM_VERIFY_CODE_ERROR);
       }
        SysUser sysUser = sysUserMapper.selectByUsername(dto.getUsername());
       if(ObjectUtils.isEmpty(sysUser)||!StringUtils.equals(sysUser.getPassword(),dto.getPassword())){
           Exceptions.cast(CodeEnum.SYSTEM_PASSWORD_ERROR);
       }
       return LoginVO.builder()
               .id(sysUser.getId())
               .username(sysUser.getUsername())
               .nickName(sysUser.getNickName())
               .phone(sysUser.getPhone()).build();
    }
}
